package com.anjufang.service.system.impl;

import com.anjufang.entity.AdminRole;
import com.anjufang.entity.AdminRoleMenu;
import com.anjufang.entity.AdminUserRole;
import com.anjufang.mapper.AdminRoleMapper;
import com.anjufang.mapper.AdminRoleMenuMapper;
import com.anjufang.mapper.AdminUserRoleMapper;
import com.anjufang.service.system.AdminRoleMenuService;
import com.anjufang.service.system.AdminRoleService;
import com.anjufang.utils.page.Query;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class AdminRoleServiceImpl implements AdminRoleService {
	
	@Autowired
	private AdminRoleMenuService roleMenuService;
	@Autowired
	private AdminRoleMapper adminRoleMapper;
	@Autowired
	private AdminRoleMenuMapper adminRoleMenuMapper;
	@Autowired
	private AdminUserRoleMapper adminUserRoleMapper;

	@Override
	public List<AdminRole> queryList(Query query) {
		
		return adminRoleMapper.queryList(query);
	}

	@Override
	public int queryTotal(Query query) {
		
		return adminRoleMapper.queryTotal(query);
	}
	
	@Override
	public AdminRole adminRole(Wrapper<AdminRoleMenu> wrapper, Long id) {
		
		AdminRole role = adminRoleMapper.selectById(id);
		//查询角色对应的菜单
		List<AdminRoleMenu> roleMenus = adminRoleMenuMapper.selectList(new EntityWrapper<AdminRoleMenu>().where("role_id ={0}", id));
		List<Long> menuIdList = new ArrayList<>();
		for (AdminRoleMenu AdminRoleMenu : roleMenus) {
			menuIdList.add(AdminRoleMenu.getMenuId());
		}
		role.setMenuIdList(menuIdList);
		return role;
	}
	
	@Override
	@Transactional
	public void addAndUpdatemenus(AdminRole role) {
		role.setCreateTime(new Date());
		role.insert();
		
		//保存角色与菜单关系
		roleMenuService.saveOrUpdate(role.getId(), role.getMenuIdList());
	}

	@Override
	@Transactional
	public void updateAndUpdatemenus(AdminRole role) {
		role.updateById();
		
		//保存角色与菜单关系
		roleMenuService.saveOrUpdate(role.getId(), role.getMenuIdList());
	}

	@Override
	public void deleteBatch(Long[] ids) {
		
		adminRoleMapper.deleteBatch(ids);
	}

	@Override
	@Transactional
	public void saveOrUpdate(Long userId, List<Long> roleIdList) {
		if(roleIdList.size() == 0){
			return ;
		}
		
		//先删除用户与角色关系
		adminUserRoleMapper.delete(new EntityWrapper<AdminUserRole>().where("user_id={0}", userId));
		
		//保存用户与角色关系
		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("roleIdList", roleIdList);
		adminUserRoleMapper.batchSave(map);
		
	}

}
